import os
import shutil
import sys
import tkinter as tk
import zipfile
from tkinter import ttk, messagebox

import pyperclip

from step.s1_power import gen_power_conf
from step.s3_genCode import generate_license_code


def on_button_click():
    os.chdir(os.path.dirname(sys.executable))
    selected_value = combobox.get()
    result = generate_license_code(selected_value)
    text.insert(tk.END, result)
    messagebox.showinfo("产品和激活码", f"{selected_value}\n{result}")
    print(result)
    pyperclip.copy(result)
    print("内容已复制到剪贴板！")


def on_button_power_click():
    os.chdir(os.path.dirname(sys.executable))
    power = gen_power_conf()
    messagebox.showinfo("提示", f"已生成，请复制到power.conf中\n{power}")
    pyperclip.copy(power)
    print(power)
    print("内容已复制到剪贴板！")


def on_button_init_click():
    print("初始化")
    base_path = os.path.dirname(__file__)
    if getattr(sys, 'frozen', False):
        # 如果是打包后的应用
        base_path = sys._MEIPASS
    target_path = os.path.dirname(sys.executable)
    print("当前路径1", base_path)
    print("当前路径2", target_path)
    messagebox.showinfo("开始初始化，请阅读说明", """如需定制化服务，请联系作者 1193136099
    
    1. 下载 GenActiveCodeMain.exe
    2. 点击初始化按钮初始化
    3. 打开GenActiveCodeMain.exe文件夹中的，解压1/jetbra.zip
    4. 执行jetbra/scripts/install-current-user.vbs
    5. 选择对应的产品，点击生成激活码按钮生成激活码
    6. 复制激活码到产品进行激活
    """)
    shutil.copytree(base_path, os.path.dirname(sys.executable), dirs_exist_ok=True)
    response = messagebox.askyesno("确认", "初始化完成,是否继续配置插件（已经配置过无需重复配置）?")
    if response:
        print("用户选择了: 是")
        target_path = target_path + "/step"
        if os.path.exists(target_path + "/1/jetbra.zip"):
            print(f"找到文件 '{target_path}' 开始执行")
        else:
            target_path = target_path.replace("\\", "/")
            target_path = target_path.replace("\\\\", "/")
            target_path = target_path.removesuffix("\\").removesuffix("/")
            print(f"文件 '{target_path}' 不存在, 尝试替换转义符")
        messagebox.showinfo("提示", "开始执行jetbra/scripts/install-current-user.vbs脚本")
        with zipfile.ZipFile(target_path + "/1/jetbra.zip", 'r') as zip_ref:
            jetbra_path = target_path + "/jetbra"
            os.makedirs(target_path + "/jetbra", exist_ok=True)
            zip_ref.extractall(jetbra_path)
            print(f"已解压 1/jetbra.zip 到 {jetbra_path}")
            print(f"start {target_path}/jetbra/jetbra/scripts/install-current-user.vbs")
            os.chdir(f"{target_path}/jetbra/jetbra/scripts/")
            os.system(f"start install-current-user.vbs")
            messagebox.showinfo("提示", """请等待..，
              如果执行失败，请手动执行jetbra/scripts/install-current-user.vbs脚本""")
    else:
        print("用户选择了: 否")


# 创建主窗口
root = tk.Tk()
root.title("Jetbrain激活码V0.4，作者QQ 1193136099")

# 设置主窗口的大小
width = 450
height = 350
root.geometry(f"{width}x{height}")
root.config(bg="#666")

# 创建下拉框
values = ["idea", "pycharm", "webstorm", "clion", "goland", "datagrip", "phpstorm"]
combobox = ttk.Combobox(root, values=values)
combobox.current(0)
# 创建按钮
button = tk.Button(root, text="生成激活码", command=on_button_click)
# 创建按钮
# button_power = tk.Button(root, text="生成power.conf", command=on_button_power_click)
# 创建按钮
init = tk.Button(root, text="初始化", command=on_button_init_click)

# 创建文本域
text = tk.Text(root, height=300 / 15, width=60)

combobox.grid(row=0, column=1, padx=5, pady=5)
init.grid(row=0, column=2, padx=5, pady=5)
# button_power.grid(row=0, column=3, padx=5, pady=5)
button.grid(row=0, column=4, padx=5, pady=5)
text.grid(row=2, columnspan=4, column=1, padx=5, pady=5)

messagebox.showinfo("更新说明", " \r\n更新说明 ；"
                                "\r\n 适配2025版本（2025不在区分社区版和专业版，不同激活码激活不同的功能）"
                                "\r\n 2024及以下版本，请继续使用0.3版本的工具即可"
                                " \r\n使用说明 ；"
                                "\r\n1. 首次使用点击初始化，点击【确认】-【是】，等待一分钟左右 会出现【Done】完成初始化 "
                                "\r\n 2. 选择产品，点击生成，将生成的激活码确认后自动复制，再idea中粘贴激活码激活即可")
# 运行主循环
root.mainloop()
